Skip to content

Support packaged dotnet run for .NET file-based apps - #874

Merged
Nikola Metulev (nmetulev) merged 12 commits into
mainfrom
azchohfi-packaged-dotnet-run-file-based-apps
Sep 18, 2026
Merged

Nikola Metulev (nmetulev) merged 12 commits into
mainfrom
azchohfi-packaged-dotnet-run-file-based-apps

Conversation

@azchohfi

Copy link
Copy Markdown
Collaborator

Description

A .NET 10 file-based app (a single .cs with #: directives) that references Microsoft.Windows.SDK.BuildTools.WinApp was never redirected by dotnet run, so it launched unpackaged. winapp run counter.cs already packaged it correctly; plain dotnet run counter.cs did not.

The cause was the run-support gate: it required an authored AppxManifest, which a file-based app has none of by design. Its identity comes from #:property directives instead.

The change has three parts:

  • Relax the gate. A new _WinAppFileBasedApp property (derived from the SDK's FileBasedProgram + EntryPointFilePath) satisfies the manifest requirement in place of an authored file. Every other condition is unchanged, so .csproj behavior is untouched.
  • Skip manifest auto-detection for file-based apps so the CLI owns all manifest resolution. An explicit #:property WinAppManifestPath= and a <stem>.appxmanifest beside the .cs both still work, because the CLI resolves them itself. This also fixes two latent bugs the old auto-detection had here: it probed the output directory first and would have pinned the stale manifest the CLI generated on a previous run, freezing identity against later #:property edits, and it would have adopted a directory-wide Package.appxmanifest that several .cs files in one folder may share.
  • Hand the .cs to the CLI's single-file mode without rebuilding. A .csproj passes its output folder, which routes the CLI into folder mode and builds nothing. A .cs cannot use folder mode because manifest inference only exists in single-file mode, so the file-based branch reproduces the same contract with --no-build plus a forwarded -p RuntimeIdentifier=$(RuntimeIdentifier). Naming the property is what suppresses the CLI's own host-RID injection; without it the CLI would read bin\debug_win-x64\ while dotnet run wrote bin\debug\, and with --no-build would silently launch a stale layout.

Worth a careful look: a fourth change came out of end-to-end testing and is the least obvious part of the PR. dotnet build app.cs records RunCommand/RunArguments in the SDK's build success cache, and a later dotnet run app.cs replays that cache instead of re-evaluating the project. ComputeRunArguments does not run during a plain build, so the SDK fell back to TargetPath and cached the bare apphost, and the next dotnet run launched the app unpackaged even though the redirect itself was configured correctly. _WinAppPrepareRunArgumentsForFileBasedBuild (AfterTargets="Build") keeps the cached entry and the redirect in agreement. It is deliberately scoped to file-based apps: a project has no such cache, and seeding run properties on every build would add loose layout copying to an ordinary dotnet build.

One deliberate scope decision: the existing windows target-platform condition is kept, so a plain net10.0 .cs is still not redirected under dotnet run. That is documented as a required condition rather than treated as a bug.

Usage Example

// counter.cs
#:package Microsoft.Windows.SDK.BuildTools.WinApp@0.6.3
#:property TargetFramework=net10.0-windows10.0.19041.0
#:property OutputType=WinExe

Console.WriteLine("hello from a packaged file-based app");
dotnet run counter.cs

Previously launched unpackaged. Now generates a manifest, registers the package, and launches with package identity, the same as winapp run counter.cs.

Related Issue

Fixes: #871

Type of Change

  • ✨ New feature

Checklist

  • New tests added for new functionality (if applicable)
  • Tested locally on Windows
  • docs/usage.md updated (if CLI commands changed)
  • Shipped skills updated in plugins/winapp/skills/ (if CLI commands/workflows changed)

Additional Notes

Testing. 25 new Pester tests in src/winapp-NuGet/tests/NuGet.Tests.ps1 cover detection, gate activation, authored manifests, run argument routing, and the run properties left behind by a plain build. Full suite passes 87/87. The three positive build-property tests were confirmed to fail with the new target removed, reproducing exactly the bug described above (RunCommand came back as the bare apphost and RunWorkingDirectory was empty), while the guard that keeps project builds untouched still passed.

Verified end-to-end against a real #:package reference to the built nupkg with the package cache purged, across five orderings: cold run, warm repeats, build-then-run, run-after-edit, and two consecutive builds. All launch packaged. Authored-manifest handling was verified the same way: a per-file counter.appxmanifest and an explicit WinAppManifestPath each win, a directory-wide Package.appxmanifest is correctly ignored, and a missing manifest path gives a clear CLI error.

scripts/build-cli.ps1 completes cleanly and docs/cli-schema.json is unchanged, since there are no CLI C# changes in this PR. validate-plugin-package.ps1 passes.

No CLI changes. The entire feature lives in the MSBuild targets. The unregister hint printed by the CLI now echoes -p RuntimeIdentifier= with an empty value; that was left alone intentionally, since suppressing empty-valued properties in general would be wrong (an empty -p WinAppPackageName= genuinely overrides a #:property back to the inferred default), and a RuntimeIdentifier-only carve-out would be arbitrary CLI special-casing driven by a targets-side decision. The printed command works verbatim as-is.

AI Description

This section is auto-generated by AI when the PR is opened or updated. To opt out, delete this entire section including the marker comments.

A .NET 10 file-based app (a single .cs with #: directives) that references
Microsoft.Windows.SDK.BuildTools.WinApp was never redirected by `dotnet run`,
because the run-support gate required an authored AppxManifest that a
file-based app has none of by design.

Relax the gate for file-based apps, skip manifest auto-detection for them so
the CLI owns all manifest resolution, and hand the .cs to the CLI's single-file
mode without rebuilding what dotnet run already built.

Also seed the run properties after Build for file-based apps. `dotnet build
app.cs` caches RunCommand/RunArguments in the SDK's build success cache and a
later `dotnet run app.cs` replays that cache; ComputeRunArguments does not run
during a plain build, so the SDK cached the bare apphost and the next run
launched the app unpackaged.

Fixes: #871

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b5760a1f-fb81-486e-bd78-337020c70571
Copilot AI balanced review requested due to automatic review settings September 18, 2026 17:37

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The hand-off breaks spaced configuration names and silently drops outer MSBuild property overrides.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Adds packaged dotnet run support for .NET file-based apps using the existing winapp packaging flow.

Changes:

  • Detects file-based apps and redirects execution through winapp.
  • Preserves packaged launch properties across build caching.
  • Adds tests and user guidance for the workflow.
File summaries
File Description
src/winapp-NuGet/tests/NuGet.Tests.ps1 Tests detection, routing, manifests, and cached run properties.
src/winapp-NuGet/README.md Documents activation and troubleshooting.
src/winapp-NuGet/build/Microsoft.Windows.SDK.BuildTools.WinApp.targets Implements file-based packaged-run redirection.
plugins/winapp/skills/winapp-setup/SKILL.md Adds setup guidance for dotnet run.
docs/usage.md Documents the user workflow and options.
docs/dotnet-run-support.md Explains the targets and file-based hand-off.
Review details

Suppressed comments (2)

src/winapp-NuGet/README.md:147

  • This heading says the new supported scenario is not intercepted, while the following text explains that interception is active for Windows-targeted file-based apps and only absent for cases such as plain net10.0. The heading should describe the condition under which interception is absent so users do not read the feature as unavailable.
### `dotnet run app.cs` is not intercepted

src/winapp-NuGet/README.md:143

  • Update the earlier manifest-gating summaries for file-based apps
  • What is wrong: The new manifest-free exception conflicts with two existing summaries: this README still says activation requires an appxmanifest, and docs/dotnet-run-support.md still lists all console apps without manifests as inactive.
  • Show me: The new condition at this line accepts a Windows file-based console app with no authored manifest, while README line 44 and docs/dotnet-run-support.md line 167 say that case is excluded.
  • Why it matters: Readers get contradictory guidance about whether the feature supports the exact scenario introduced by this pull request.
  • Smallest fix: Qualify those summaries as project-based behavior or explicitly mention the file-based-app exception.
5. Either a manifest exists in the project directory (`Package.appxmanifest`, `AppxManifest.xml`, or `appxmanifest.xml`) or you explicitly set `WinAppManifestPath` to a file that exists — **or** the project is a .NET file-based app (a single `.cs` run with `dotnet run app.cs`), which has no authored manifest by design and gets its identity inferred instead.
  • Files reviewed: 6/6 changed files
  • Comments generated: 3
  • Review effort level: Balanced

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/winapp-NuGet/README.md Resolved
`dotnet run app.cs -p:WinAppPackageName=Contoso` built with Contoso but
registered the inferred hashed identity instead. The CLI re-evaluates the .cs
to plan the manifest, and that evaluation cannot see the properties the outer
build was invoked with, so the override was silently lost between the two.

The run hand-off now carries the effective value of every identity-shaping
property winapp reads, when non-empty: WinAppPackageName, WinAppDisplayName,
WinAppPublisher, WinAppVersion, WinAppDescription, WinAppCapabilities and
WinAppManifestPath. Forwarding a value that came from a `#:property` directive
is a no-op because the CLI reads the directive itself; empty values are never
forwarded, since the CLI treats a named property as an explicit request and an
empty one would override a directive back to the inferred default.

Also quotes the forwarded configuration and RuntimeIdentifier so a value
containing spaces survives argv splitting, and fixes the docs that suggested
`dotnet msbuild app.cs` as the diagnostic command - msbuild cannot load a .cs,
only `dotnet build app.cs` synthesizes the virtual project. Qualifies the two
manifest-gating summaries that read as unconditional now that file-based apps
are an exception.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b5760a1f-fb81-486e-bd78-337020c70571
…e-based-apps' into azchohfi-packaged-dotnet-run-file-based-apps

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The hand-off can lose build overrides and incorrectly serialize forwarded property values.

Get a fresh assessment by requesting another Copilot review.

Review details
  • Files reviewed: 6/6 changed files
  • Comments generated: 2
  • Review effort level: Balanced

…nd-off

The redirect passes the .cs to `winapp run --no-build`, so the CLI evaluates the
app a second time to plan the manifest. That second evaluation cannot see the
properties the outer build was invoked with, which is why the identity
properties are forwarded explicitly. Two gaps remained.

The forwarding set only covered the WinApp* identity properties, so overrides
that decide *what* gets packaged were silently dropped. `dotnet run app.cs
-p:AssemblyName=Foo` built Foo.exe but wrote an Executable of app.exe into the
manifest, and `-p:Version=2.3.4.5` registered as 1.0.0.0. Adds the remaining
properties the CLI's evaluate pass reads: AssemblyName, OutputPath, OutputType,
TargetFramework, Version, WindowsPackageType and WindowsAppSDKSelfContained. The
SDK's derived outputs (TargetDir, RunCommand, RunArguments, ProjectAssetsFile)
stay out so the CLI still derives them itself.

Values were also spliced in raw. The CLI rejects a -p token containing ';' or
',', so `#:property WinAppCapabilities=internetClient;privateNetworkClientServer`
failed the run outright, and OutputPath's trailing backslash would escape the
closing quote of its own argument. Forwarded values are now percent-escaped the
same way the CLI escapes its own (%, ';', ',', '"', '\'), with percent first so
the encoding stays reversible. Exec writes a temporary .cmd where cmd.exe eats
'%N' as a batch parameter, so RunPackagedApp uses a percent-doubled spelling of
the same arguments while RunArguments, which dotnet run invokes directly, keeps
the undoubled one.

Adds two test contexts covering the forwarded build inputs and the escaping of
each separator, and documents both in docs/dotnet-run-support.md.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b5760a1f-fb81-486e-bd78-337020c70571

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The cross-boundary MSBuild argument handling remains complex and has an unresolved value-corruption defect.

Review details

Suppressed comments (2)

src/winapp-NuGet/build/Microsoft.Windows.SDK.BuildTools.WinApp.targets:394

  • Explicit empty -p overrides are lost here. For example, a file with #:property WinAppManifestPath=custom.appxmanifest invoked as dotnet run app.cs -p:WinAppManifestPath= evaluates the outer build with the property cleared, but these != '' filters omit it, so winapp re-evaluates without the override and still selects custom.appxmanifest (the same applies to WinAppPackageName=). The CLI treats an empty value as a clear (SingleFileManifestPlanner.Read maps it to absent), so preserve whether the property was explicitly supplied and forward Name= for that case, or otherwise make the hand-off honor empty overrides.
      Empty values are skipped rather than forwarded. Winapp treats a named property as an
      explicit request, so passing an empty one would override a directive back to the inferred
      default instead of leaving it alone.

src/winapp-NuGet/build/Microsoft.Windows.SDK.BuildTools.WinApp.targets:394

  • Preserve empty property overrides during the second evaluation
  • What is wrong: Skipping empty effective values loses an explicit -p clear when the .cs contains a directive.
  • Show me: counter.cs sets #:property WinAppPackageName=FromDirective; dotnet run counter.cs -p:WinAppPackageName= builds with the inferred hashed name, but these conditions omit the empty property, so winapp re-evaluates the directive and registers FromDirective instead. The same mismatch applies to WinAppManifestPath and the other forwarded properties.
  • Why it matters: A valid MSBuild override can make the packaged identity/manifest differ from the app that dotnet run built; the PR description explicitly treats an empty WinAppPackageName as a meaningful reset.
  • Smallest fix: Preserve the effective empty value across the CLI hand-off (and add a regression with a directive plus -p:WinAppPackageName=), while still avoiding accidental defaults where necessary.
      Empty values are skipped rather than forwarded. Winapp treats a named property as an
      explicit request, so passing an empty one would override a directive back to the inferred
      default instead of leaving it alone.
  • Files reviewed: 6/6 changed files
  • Comments generated: 1
  • Review effort level: Balanced

Two defects in the file-based run argument hand-off, both found by review.

An apostrophe in a forwarded value silently corrupted it. The batched
`Update="@(_WinAppForwardedProperty)"` escape put `%(Value)` inside a
single-quoted property-function argument, so `Bob's App` terminated the
string literal and MSBuild emitted the unevaluated expression text as the
value. Each property now escapes itself with the property-instance form
`$(X.Replace(...))`, where the value is never part of the expression source.
MSBuild offers no per-item escape that avoids embedding the value in an
argument, so the 14 lines are deliberately repetitive.

An explicit `-p:WinAppPackageName=` could not clear a `#:property`
directive, because the forwarding condition dropped empty values and the
inner evaluation then re-read the directive. The seven identity properties
now forward unconditionally; the CLI maps absent and empty alike to "not
set", so this is a no-op when nothing set the property. Build inputs keep
the condition, since the SDK always supplies a value and forwarding an
empty global would suppress the default.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b5760a1f-fb81-486e-bd78-337020c70571

@nmetulev Nikola Metulev (nmetulev) left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 AI-generated review (winappcli pr-review skill) — verify before acting.

Requesting changes for one remaining launch failure.

Preserve redirected build output in the hand-off

What is wrong: The targets forward OutputPath, but not OutDir or the resolved TargetDir. OutDir can independently change where MSBuild writes the executable, so winapp's second evaluation can point at a different directory from the one just built.

Show me: With a Windows file-based console app referencing this package:

dotnet run counter.cs -p:OutDir=.\custom-output\

The build succeeds and writes custom-output\counter.exe, but winapp exits 1 with "The build output directory for 'counter.cs' does not exist", naming the default temporary bin\debug directory. Passing the same OutDir property directly to winapp run succeeds.

Why it matters: A successful build cannot launch. If the default directory already contains an older build, the hand-off can instead package stale binaries.

Smallest fix: Carry the effective output location into the CLI evaluation by forwarding OutDir or the resolved TargetDir, and add an end-to-end regression case with redirected output.

Location: Microsoft.Windows.SDK.BuildTools.WinApp.targets, line 435.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

Copilot was unable to run its full agentic suite in this review.

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated 6 comments.

Comment thread src/winapp-NuGet/tests/NuGet.Tests.ps1 Resolved
Comment thread src/winapp-NuGet/tests/NuGet.Tests.ps1 Resolved
Comment thread src/winapp-NuGet/tests/NuGet.Tests.ps1 Resolved
Comment thread src/winapp-NuGet/tests/NuGet.Tests.ps1 Resolved
…ID notes

Review follow-ups, none of which change the shipped hand-off.

The file-based tests claimed to run "outside any global.json", but nothing
established that: SDK selection follows the CURRENT directory, not the
project being built, so `dotnet build <temp>\app.cs` launched from the repo
reads the repo's global.json and ignores one sitting beside app.cs. Verified
directly: a bogus pin next to the .cs is ignored from the repo, and fatal
once that directory is the working directory. The three helpers now share one
invoker that pushes to the app's directory, which makes the comment true and
keeps the newest-installed-SDK skip logic honest if a pin is ever added.

Two comments described the RuntimeIdentifier token as always passing an empty
value. It passes the effective value through, which is what keeps the CLI and
dotnet on the same output folder: an unqualified build has no RID, and naming
the property empty suppresses the CLI's host-RID injection, but a build that
sets one writes bin\debug_<rid>\, so blanking the value there would recreate
the mismatch the token exists to prevent. Confirmed by evaluating OutputPath
with and without a RID. A new test pins the pass-through so the empty-value
reading cannot be restored by a later "fix".

Also relabels the diagnostic that printed the pre-transport argument string
under a "Command:" heading while Exec ran the percent-doubled spelling, and
puts a BeforeAll that had been left on the Context line back on its own line.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b5760a1f-fb81-486e-bd78-337020c70571

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Explicit empty packaging and alias overrides are lost during the CLI hand-off, causing behavior to differ from the requested configuration.

Review details

Suppressed comments (2)

Previously missed (1) — in code that hasn't changed since the last review.

src/winapp-NuGet/build/Microsoft.Windows.SDK.BuildTools.WinApp.targets:446

  • Explicit empty overrides are lost during CLI re-evaluation
  • What is wrong: The hand-off omits WindowsPackageType when its effective value is empty and never forwards an empty WinAppRunUseExecutionAlias. Winapp then re-evaluates the .cs and reads the original directives again.
  • Show me: For a file containing #:property WindowsPackageType=None, dotnet run app.cs -p:WindowsPackageType= activates the outer packaged gate, but the generated arguments contain no WindowsPackageType property, so winapp sees None again. Likewise, clearing #:property WinAppRunUseExecutionAlias=true emits neither an alias switch nor an empty property, so the CLI sees true again instead of restoring its default.
  • Why it matters: Valid command-line clears can launch with the wrong packaging or alias behavior.
  • Smallest fix: Forward WindowsPackageType even when empty, and carry an empty WinAppRunUseExecutionAlias only when its effective value is empty so the existing true/false switch precedence remains unchanged. Add regression tests for both clears.

src/winapp-NuGet/build/Microsoft.Windows.SDK.BuildTools.WinApp.targets:683

  • Diagnostic points to an uncomputed property
  • What is wrong: WinAppRunSupportInfo tells users to query RunArguments, but it does not run _WinAppBuildRunArgs or _WinAppPrepareRunArguments first.
  • Show me: dotnet build app.cs -t:WinAppRunSupportInfo -getProperty:RunArguments succeeds but returns an empty value instead of the redirected run "app.cs" --no-build ... arguments.
  • Why it matters: The suggested troubleshooting step hides the command users need to inspect.
  • Smallest fix: Point the message at _WinAppBuildRunArgs and _WinAppRunArgs, which actually compute and expose the CLI arguments.
    <Message Text="(For the exact CLI command, query -getProperty:RunArguments.)" Importance="high" />
  • Files reviewed: 6/6 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

A `dotnet run app.cs -p:WindowsPackageType=` over a `#:property
WindowsPackageType=None` activated the packaged redirect but forwarded no
value, so winapp re-read `None` and treated the run as unpackaged. Same for
`-p:WinAppRunUseExecutionAlias=`: `true`/`false` ride on the
`--with-alias`/`--without-alias` switch, but a clear emits no switch, so the
directive survived a command line that turned it off.

Forward `WindowsPackageType` unconditionally, and `WinAppRunUseExecutionAlias`
only when empty, which leaves the switch precedence (including the deliberate
suppression under `--detach`/`--no-launch`) untouched.

Also point `WinAppRunSupportInfo` at a command that actually prints the
arguments; it advertised `-getProperty:RunArguments`, which that target never
computes.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b5760a1f-fb81-486e-bd78-337020c70571
@azchohfi

Copy link
Copy Markdown
Collaborator Author

Round 5's two suppressed findings were both real. Fixed in 784d9d0.

1. Explicit clears of WindowsPackageType and WinAppRunUseExecutionAlias were lost

Probed against the shipped targets:

wpt.cs with #:property WindowsPackageType=None, run as -p:WindowsPackageType=:

gate : true
args : ...no WindowsPackageType token at all...

The outer gate activates the packaged redirect, then winapp re-evaluates the .cs, reads None from the directive, and treats the run as unpackaged.

al.cs with #:property WinAppRunUseExecutionAlias=true:

control (directive true) -> switch=--with-alias     property=not forwarded
cleared (-p:...=)        -> switch=(none)           property=not forwarded
false   (-p:...=false)   -> switch=--without-alias  property=not forwarded

true/false ride on the switch, but a clear emits no switch, so winapp keeps the directive value.

Fixes: WindowsPackageType now forwards unconditionally (an ordinary packaged .cs evaluates it empty anyway, so the common case is unchanged); WinAppRunUseExecutionAlias forwards only when empty, which leaves the switch precedence intact, including the deliberate case where --detach/--no-launch withholds the alias switch while the property is true. Two regression tests added, one per property, plus the existing test pinning that true/false still forward no property. Suite: 114/114.

2. WinAppRunSupportInfo advertised a property it never computes

dotnet build wpt.cs -t:WinAppRunSupportInfo -getProperty:RunArguments  ->  []

The target has no DependsOnTargets. I deliberately did not make it depend on _WinAppBuildRunArgs: that target is gated on _WinAppRunSupportActive and depends on _WinAppValidateRunSupport, which can raise errors, and a diagnostic target should not fail. The message now points at the one-liner that does work: -t:_WinAppBuildRunArgs -getProperty:_WinAppRunArgs.

docs/dotnet-run-support.md updated for the three forwarding tiers. build-cli.ps1 and validate-plugin-package.ps1 both green; cli-schema.json unchanged.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

MSBuild interception, argument transport, manifest identity, and SDK cache behavior warrant final human Windows validation.

Review details
  • Files reviewed: 6/6 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

@github-actions

github-actions Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

⏳ Build in progress — metrics below are from a previous commit and will update when the current build finishes.

Build Metrics Report

Binary Sizes

Artifact Baseline Current Delta
CLI (ARM64) 56.89 MB 56.89 MB ✅ 0.0 KB (0.00%)
CLI (x64) 56.94 MB 56.94 MB ✅ 0.0 KB (0.00%)
MSIX (ARM64) 23.65 MB 23.65 MB 📉 -0.0 KB (-0.00%)
MSIX (x64) 25.10 MB 25.10 MB 📈 +0.4 KB (+0.00%)
NPM Package 49.33 MB 49.33 MB 📈 +0.2 KB (+0.00%)
NuGet Package 49.42 MB 49.43 MB 📈 +9.4 KB (+0.02%)

Test Results

✅ 7494 passed, 37 skipped out of 7531 tests in 1321.0s (-178.7s vs. baseline)

Test Coverage

✅ 86% line coverage, 80.2% branch coverage · ✅ no change vs. baseline

CLI Startup Time

62ms median (x64, winapp --version) · ✅ no change vs. baseline

Try This Build

Installs the MSIX for your architecture, replacing any previously installed build. Needs the GitHub CLI — the command offers to install it and sign you in if it is missing.

& ([scriptblock]::Create((irm https://raw.githubusercontent.com/microsoft/winappCli/main/scripts/winapp-pr.ps1))) 874
Switching between builds often?

Put the tool on your PATH once:

& ([scriptblock]::Create((irm https://raw.githubusercontent.com/microsoft/winappCli/main/scripts/winapp-pr.ps1))) -AddToPath

Then this build is just:

winapp-pr 874

Run winapp-pr with no arguments to pick from a list of open PRs.


Updated 2026-09-18 21:09:15 UTC · commit 784d9d0 · workflow run

`dotnet run counter.cs -p:OutDir=.\custom-output\` built to custom-output but
handed winapp only OutputPath, which `-p:OutDir` leaves at the default
bin\debug\. The run then failed with "Executable 'counter.exe' (from manifest)
was not found in the output directory", or packaged a stale build when that
directory still held one.

OutDir is the property MSBuild actually writes the executable to, and TargetDir
-- what the CLI resolves the layout from -- is just its absolute form, so
naming OutDir is what steers the second evaluation. The effective value is
forwarded as-is even when relative, since MSBuild resolves it against the
project directory, which for a file-based app is the directory holding the .cs.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b5760a1f-fb81-486e-bd78-337020c70571
@azchohfi

Copy link
Copy Markdown
Collaborator Author

Nikola Metulev (@nmetulev) thanks - this was real, and my review polling had been filtering on the Copilot bot login so I missed your review until now. Sorry about that. Fixed in c7a8d28.

Root cause

OutDir, not OutputPath, is the property MSBuild writes the executable to. OutDir defaults to OutputPath, but setting it moves the output while leaving OutputPath alone, so the two diverge:

                default                          -p:OutDir=.\custom-output\
OutputPath   ...runfile\od-<hash>\bin\debug\   ...runfile\od-<hash>\bin\debug\   <- unchanged
OutDir       ...runfile\od-<hash>\bin\debug\   .\custom-output\
TargetDir    ...runfile\od-<hash>\bin\debug\   ...\winapp-probe-outdir\custom-output\

The hand-off forwarded only OutputPath, so winapp's second evaluation re-derived TargetDir from the default and looked in a directory the build never wrote to. My code comment claiming "OutputPath IS forwarded, and TargetDir follows from it" was simply wrong: TargetDir follows from OutDir.

Before / after, replaying the exact argument list against the packed CLI:

# without the OutDir token (old hand-off)
winapp run counter.cs --no-build -c Debug -p OutputPath=<temp>\bin\debug\ ...
  -> exit 1
  Executable 'counter.exe' (from manifest) was not found in the output directory

# with -p OutDir=.%5Ccustom-output%5C (new hand-off)
  -> exit 0, OutDirProbe_gspb8g6x97k2t registered

And the real thing end to end, from a clean temp app:

dotnet run fresh.cs -p:OutDir=.\redirected\ -p:WinAppRunUseExecutionAlias=true
  -> OutDirFresh_gspb8g6x97k2t registered
  -> fresh redirected run
  -> exit 0

The fix

Forward OutDir alongside OutputPath in the build-inputs tier. Both are kept: OutputPath still feeds ResolveSingleFileBuildRoot, which uses the SDK's canonical temp root to decide whether a registration belongs to this .cs, and that root should not move when a user redirects output.

The effective value is forwarded as-is even when relative. I verified MSBuild resolves a relative OutDir against the project directory, which for a file-based app is the directory holding the .cs, so both passes land on the same folder regardless of where either was launched from:

cwd = .cs dir        -> TargetDir = ...\winapp-probe-outdir\custom-output\
cwd = %USERPROFILE%  -> TargetDir = ...\winapp-probe-outdir\custom-output\

Tests (suite now 116/116): one pinning that OutDir is forwarded and that OutputPath still reports the default, since it is their divergence the old hand-off got wrong; and a round-trip that replays only the forwarded, percent-escaped token and asserts the resulting TargetDir equals the one the build used.

One thing I deliberately did not change. WinAppLooseLayoutPath still defaults to $(OutputPath)AppX\, so with a redirected OutDir the AppX layout stays in the SDK's build directory rather than moving next to the binaries. I checked this from a clean state and it is where a non-redirected run puts it too, and the run succeeds, so it is consistent rather than broken. The same default is shared with project mode, where _WinAppInputFolderArg is also OutputPath-based, so OutDir has the same blind spot for a .csproj. That is pre-existing shipped behavior and a wider change than this PR, so I left it alone. Happy to file it as a follow-up if you want it fixed.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

The hand-off still has architecture, argument-escaping, and assets-graph correctness issues.

Get a fresh assessment by requesting another Copilot review.

Review effort: Balanced
Findings: 1 High severity

Open (1)
Previously missed (2)

In code that hasn't changed since last review

Medium severity Escape Configuration before quoting the Windows command argument

src/​winapp-NuGet/​build/​Microsoft.Windows.SDK.BuildTools.WinApp.targets:363

Escape the configuration before quoting it

  • What is wrong: Configuration is inserted raw into a quoted Windows command-line argument, unlike the other forwarded values.
  • Show me: dotnet run counter.cs -p:Configuration=Debug\ builds the custom configuration, but the trailing backslash escapes the closing quote and winapp parses the remaining properties and options as part of the configuration value.
  • Why it matters: The redirected run fails to launch for an otherwise valid custom configuration.
  • Smallest fix: Apply the same reversible percent-escaping used for forwarded property values, and add a trailing-backslash regression test.
Medium severity Forward the effective ProjectAssetsFile to the no-build evaluation

src/​winapp-NuGet/​build/​Microsoft.Windows.SDK.BuildTools.WinApp.targets:481

Pass the assets graph produced by the outer build

  • What is wrong: The hand-off excludes ProjectAssetsFile, but it also omits inputs such as BaseIntermediateOutputPath that determine where that file is written.
  • Show me: dotnet build counter.cs -p:BaseIntermediateOutputPath=custom_obj\ evaluates ProjectAssetsFile as custom_obj\project.assets.json, while _WinAppRunArgs forwards neither value. Winapp therefore re-evaluates the default obj\project.assets.json path.
  • Why it matters: Package discovery can use the wrong graph, so conditional Windows App SDK dependencies may be omitted from provisioning or the generated manifest.
  • Smallest fix: Forward the escaped effective ProjectAssetsFile to the no-build evaluation and add coverage for a relocated intermediate directory.

@nmetulev Nikola Metulev (nmetulev) left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 AI-generated review (winappcli pr-review skill) — verify before acting.

Requesting changes for three remaining defects. c7a8d286 addresses the previous OutDir finding, so it is not repeated here. The failures below were reproduced on Windows x64 / .NET SDK 10.0.401 at 784d9d0a; I inspected the subsequent commit and confirmed these paths remain unchanged.

1. Multiline metadata can execute batch commands

What is wrong: RunPackagedApp inserts forwarded properties into an Exec batch file without escaping or rejecting carriage returns/newlines. A multiline description can therefore become separate shell commands. Ordinary dotnet run uses a different, shell-free launch path.

Show me: In a Windows file-based app referencing this package, with no description directive, this harmless probe executes a separate echo command:

$env:WinAppDescription = "first`r`necho WINAPP_REDTEAM_R2`r`nrem "
try {
    dotnet build .\counter.cs --no-restore -t:RunPackagedApp `
        "-p:WinAppCliPath=$env:WINDIR\System32\whoami.exe"
} finally {
    Remove-Item Env:\WinAppDescription
}

whoami.exe rejects the launcher arguments, but the batch interpreter also prints a standalone WINAPP_REDTEAM_R2: the description was executed rather than kept as data. Substituting a harmless system executable avoids package registration during this probe.

Why it matters: Metadata supplied through an environment variable is interpreted as commands, without requiring an authored MSBuild target to execute them.

Smallest fix: Reject CR/LF in the assembled command before Exec, with an actionable error and a regression test using a harmless launcher.

Location: Microsoft.Windows.SDK.BuildTools.WinApp.targets:429, lines 535–562.

2. Relocating intermediate output can package stale runtime requirements

What is wrong: The hand-off omits ProjectAssetsFile, which records the packages resolved for the build, and does not preserve the properties that relocate it. The CLI's second evaluation can read an older assets file from the default location.

Show me: Build a framework-dependent Windows App SDK file-based app with package version 1.8.250907003. Change its reference to 1.8.260101001, then run:

dotnet run .\app.cs "-p:BaseIntermediateOutputPath=$PWD\new-obj\"

The new assets file resolves 1.8.260101001, but winapp reads the old default assets file. The generated manifest requires runtime 8000.616.304.0 instead of 8000.731.1532.0. Passing the new ProjectAssetsFile explicitly to winapp run --no-build generates the correct requirement.

Why it matters: The package declares runtime requirements for an older build, so registration can succeed on a machine whose runtime does not satisfy the executable just built.

Smallest fix: Forward the effective ProjectAssetsFile through the existing escaped-property mechanism and cover a package-version update with relocated intermediate output.

Location: Microsoft.Windows.SDK.BuildTools.WinApp.targets:380–384.

3. Clearing self-contained mode produces a broken package

What is wrong: An empty WindowsAppSDKSelfContained override is omitted. Winapp then rereads a true directive from the source and assumes the Windows App SDK runtime is bundled, although the outer build excluded it.

Show me: With a Windows App SDK 1.8.260101001 file-based app declaring RuntimeIdentifier=win-x64 and WindowsAppSDKSelfContained=true, run:

dotnet run .\app.cs -p:WindowsAppSDKSelfContained=

The build succeeds, but the generated manifest lacks the Windows App Runtime dependency and the output contains no bundled runtime DLL. Calling Microsoft.Windows.AppLifecycle.AppInstance.GetCurrent() crashes with 0x80040154 — Class not registered. Direct winapp run --no-build with -p RuntimeIdentifier=win-x64 -p WindowsAppSDKSelfContained= succeeds.

Why it matters: A valid command-line override creates a package missing the runtime its executable needs.

Smallest fix: Forward WindowsAppSDKSelfContained even when empty, as already done for WindowsPackageType, and add a directive-plus-empty-override regression test.

Location: Microsoft.Windows.SDK.BuildTools.WinApp.targets:481.

Two more places where the file-based hand-off lost, or mangled, an input the
CLI's second evaluation depends on.

Configuration was spliced raw into a quoted argument. MSBuild does not validate
it, so `dotnet run app.cs -p:Configuration=Debug\` builds happily and then emits
`--configuration "Debug\"`, where the backslash escapes the closing quote and
swallows every property and switch after it into the configuration name. It now
carries the same percent-escaping as the forwarded properties. RuntimeIdentifier
is escaped alongside it to keep the rule uniform, though the SDK rejects a
malformed RID long before this target runs.

ProjectAssetsFile was excluded as a derived output on the assumption that its
inputs were forwarded, but none of them were -- the same mistake the OutDir fix
corrected for TargetDir. `-p:BaseIntermediateOutputPath=custom_obj\` moves
project.assets.json out of the SDK's runfile folder, so the CLI re-derived the
default path and read a stale package graph or none at all, quietly dropping the
conditional Windows App SDK dependencies that decide provisioning and the
generated manifest. MSBuildProjectExtensionsPath is now forwarded, which covers
a relocation spelled either way and lets ProjectAssetsFile follow.

Also documents that a file-based app must declare an architecture: `winapp run`
injects a host RID when the file names none, but `dotnet run` cannot, since
silently changing the architecture of a build the user invoked directly would
move the output from under them.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b5760a1f-fb81-486e-bd78-337020c70571
@azchohfi

Copy link
Copy Markdown
Collaborator Author

Round 7: both suppressed findings were real and are fixed in 7ad9892. The open inline finding is answered in its own thread.

Escape the configuration before quoting it

Confirmed. MSBuild does not validate Configuration, so the hostile value builds fine and the bad argument really is emitted:

dotnet run counter.cs -p:Configuration=Debug\
  -> run "...\counter.cs" --no-build --configuration "Debug\" -p "RuntimeIdentifier=" ...

\" is an escaped quote in argv, so the configuration name runs on through every property and switch after it. Now:

  -> run "...\counter.cs" --no-build --configuration "Debug%5C" -p "RuntimeIdentifier=" ...

I escaped RuntimeIdentifier on the same line for uniformity, but I want to be straight about that half: I could not demonstrate it. My first regression test declared RuntimeIdentifier=win-x64;Smuggled=true and the SDK rejected it with NETSDK1083 during evaluation, before _WinAppBuildRunArgs ever ran. So a ; can never reach that token, the escape there is belt-and-braces, and I dropped the test rather than keep one that pins an unreachable state. The comment says so instead of claiming a threat that does not exist. Only the Configuration case has a test.

Pass the assets graph produced by the outer build

Confirmed, and this is the same mistake the OutDir fix corrected for TargetDir: a derived output was excluded on the theory that its inputs were forwarded, when in fact none of them were.

                    default                                with -p:BaseIntermediateOutputPath=custom_obj\
ProjectAssetsFile   ...runfile\counter-<hash>\obj\         ...\winapp-probe-r7\custom_obj\
                      project.assets.json                    project.assets.json

The hand-off forwarded neither value, so the CLI re-derived the runfile path and read a stale package graph or none at all. Since ProjectAssetsFile feeds ProjectAssetsFileReader.TryRead for package discovery, that is where conditional Windows App SDK dependencies would go missing from provisioning and the generated manifest.

Fix: forward MSBuildProjectExtensionsPath rather than ProjectAssetsFile itself. It is the folder the assets file is written into, so the derived path follows, and naming the input covers a relocation spelled as either BaseIntermediateOutputPath or MSBuildProjectExtensionsPath. It is also always absolute, so unlike OutDir there is no relative-resolution question, and in the default case it resolves to the same runfile folder the CLI would have computed anyway. Verified the escaped form round-trips:

-p "MSBuildProjectExtensionsPath=C:%5C...%5Ccustom_obj%5C"  ->  ProjectAssetsFile = ...\custom_obj\project.assets.json

The new test does the full round trip: resolve ProjectAssetsFile from a build with a relocated obj, pull the forwarded token back out of the computed arguments, replay it in a fresh evaluation, and assert it lands on the same file.

Suite is 118/118; build-cli.ps1 and validate-plugin-package.ps1 both clean, with cli-schema.json unchanged.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread src/winapp-NuGet/tests/NuGet.Tests.ps1 Resolved
…anifest

Three defects in the file-based hand-off, all reachable from an ordinary
dotnet run:

RunPackagedApp passes the assembled arguments to Exec, which writes them to a
temporary command script. A newline inside a forwarded value did not stay data
there: it ended the line and ran the remainder as a separate command. MSBuild
takes properties from the environment, so a variable of the matching name was
enough to plant one. No manifest metadata is legitimately multi-line, so the
build is now refused with a message naming the properties to check, rather
than silently stripped, which would register an identity the consumer never
asked for. The guard sits in _WinAppBuildRunArgs, so both transports are
covered.

WindowsAppSDKSelfContained sat with the build inputs, which are forwarded only
when set on the grounds that the SDK always gives them a value. Nothing gives
this one a default, so clearing it was dropped and winapp re-read the
#:property directive, generating a manifest that required the Windows App
Runtime for a build that no longer bundled it. It moves next to
WindowsPackageType, forwarded even when empty.

Manifest existence was not validated for a file-based app. Auto-detection is
skipped entirely there, so a non-empty WinAppManifestPath is always something
the consumer set, and a typo is worth catching where the message can name the
resolved path. The "no manifest at all" error stays suppressed, since a
file-based app is expected to have none.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b5760a1f-fb81-486e-bd78-337020c70571
The escape chain is repeated per property, so the risk worth testing is not
the repetition itself but a repetition that silently drifts. This drives one
hostile value through the whole forwarded set in a single evaluation and
asserts every token arrives escaped, and that the raw value appears nowhere
in the command line.

Verified by mutation: dropping only the semicolon escape from WinAppPublisher
turns this test red.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b5760a1f-fb81-486e-bd78-337020c70571
@azchohfi

Copy link
Copy Markdown
Collaborator Author

Nikola Metulev (@nmetulev) thanks - all three reproduced, and two of them were real. Fixed in a73a311.

1. Line break in a forwarded value executes a second command

Reproduced exactly as you described. WINAPP_REDTEAM_R2 came out as a standalone line, which only happens if echo ran as its own batch command:

EXEC : error : Invalid argument/option - 'run'.
  WINAPP_REDTEAM_R2
error MSB3073: The command ""whoami.exe" run "counter.cs" ... -p "WinAppDescription=first
error MSB3073: echo WINAPP_REDTEAM_R2
error MSB3073: rem " -p "WinAppCapabilities=" ...

Fixed by rejecting it, not escaping it. No manifest metadata is legitimately multi-line, so silently stripping the newline would register an identity the consumer never asked for. The build now fails with a message naming the properties to check.

The guard sits in _WinAppBuildRunArgs rather than in RunPackagedApp, so it covers the dotnet run path too. That path cannot execute the tail, but a split argument list still corrupts the launch there.

Two mechanics worth recording, since both are easy to get wrong:

  • %0D / %0A in a targets file are MSBuild escapes for the characters themselves, so the probe properties hold one real character each. Verified before relying on it (Length of 1, abc%0Adef measuring 7).
  • The result is kept in a boolean property and the condition tests only that boolean. Expanding the value inside the condition would reintroduce the apostrophe-corruption bug this PR already fixed once. Control test: WinAppDescription=Bob's cool app still forwards intact.

On severity, to be straight with you: anyone who can set your environment variables can already run code during a build, so this is defense in depth rather than a broken trust boundary. It is still worth closing, because the failure mode is silent and the blast radius is a shell command rather than a bad string.

2. Relocated intermediate output packages a stale runtime requirement

This one was already fixed in 7ad9892, before your review landed. I verified it covers your exact repro:

-p:BaseIntermediateOutputPath=<dir>\new-obj\
  -> -p "MSBuildProjectExtensionsPath=...%5Cnew-obj%5C"

I forwarded the folder rather than ProjectAssetsFile itself. ProjectAssetsFile is derived as $(MSBuildProjectExtensionsPath)project.assets.json, so naming the input covers a relocation spelled as either BaseIntermediateOutputPath or MSBuildProjectExtensionsPath and lets the derived file follow. It also keeps ProjectAssetsFile off the forwarded list, which matters because forcing a derived output as a global property would override winapp's own evaluation instead of letting it compute the same answer.

3. Clearing self-contained mode produced a broken package

Confirmed. dotnet run app.cs -p:WindowsAppSDKSelfContained= emitted no token at all, so winapp re-read the #:property directive.

The root cause was a miscategorization rather than a missing case. The property sat in the "build inputs, forwarded only when set" group, whose justification is that the SDK always gives those a value, so an empty one means the outer build is already broken. That is true of AssemblyName, OutputPath, OutDir, OutputType, TargetFramework and Version. It is not true of WindowsAppSDKSelfContained, which nothing defaults, so an empty value there is a real answer. It now sits next to WindowsPackageType and is forwarded even when empty.

After:

default (directive true) -> -p "WindowsAppSDKSelfContained=true"
-p:WindowsAppSDKSelfContained= -> -p "WindowsAppSDKSelfContained="

Also in this push

Copilot's round-8 review found that manifest existence was never validated for a file-based app. Since auto-detection is skipped entirely in that mode, a non-empty WinAppManifestPath is always consumer-set, so a typo now fails fast naming the path. That check immediately caught an existing test that had been using WinAppManifestPath as a throwaway carrier for a trailing backslash.

Regression tests for all of the above: 123 passing. build-cli.ps1 and validate-plugin-package.ps1 both green, cli-schema.json unchanged.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support packaged dotnet run for .NET file-based apps (.cs) via the BuildTools.WinApp targets

3 participants